<template>
  <div class="category-page">
    <a-page-header title="分类管理" sub-title="管理家教科目分类"/>

    <a-card class="card-shadow">
      <template #extra>
        <a-button type="primary" @click="showAddModal">
          <template #icon>
            <plus-outlined/>
          </template>
          添加分类
        </a-button>
      </template>

      <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div :style="{ paddingLeft: `${record.level * 20}px` }">
              <span v-if="record.level > 0" style="color: #999; margin-right: 8px;">└─</span>
              {{ record.name }}
            </div>
          </template>

          <template v-else-if="column.key === 'icon'">
            <a-avatar v-if="record.icon" :src="record.icon" shape="square"/>
            <span v-else style="color: #999;">-</span>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-switch
                v-model:checked="record.isActive"
                checked-children="启用"
                un-checked-children="禁用"
                @change="handleStatusChange(record)"
            />
          </template>

          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-popconfirm
                  title="确定要删除此分类吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="handleDelete(record)"
              >
                <a-button type="link" danger size="small">
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑弹窗 -->
    <a-modal
        v-model:open="modalVisible"
        :title="modalTitle"
        @ok="handleSubmit"
        @cancel="handleCancel"
    >
      <a-form :model="formData" :label-col="{ span: 6 }">
        <a-form-item label="分类名称" required>
          <a-input v-model:value="formData.name" placeholder="请输入分类名称"/>
        </a-form-item>

        <a-form-item label="分类描述">
          <a-textarea
              v-model:value="formData.description"
              placeholder="请输入分类描述"
              :rows="4"
          />
        </a-form-item>

        <a-form-item label="图标URL">
          <a-input v-model:value="formData.icon" placeholder="请输入图标URL"/>
        </a-form-item>

        <a-form-item label="父分类">
          <a-tree-select
              v-model:value="formData.parentId"
              :tree-data="categoryTreeData"
              placeholder="请选择父分类（不选则为顶级分类）"
              allow-clear
              :field-names="{ label: 'name', value: 'id', children: 'children' }"
          />
        </a-form-item>

        <a-form-item label="排序">
          <a-input-number
              v-model:value="formData.sort"
              :min="0"
              :max="999"
              placeholder="数字越小越靠前"
              style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import {message} from 'ant-design-vue'
import {PlusOutlined} from '@ant-design/icons-vue'
import {
  getCategoryTree,
  createCategory,
  updateCategory,
  deleteCategory,
  updateCategoryStatus
} from '@/api/category'

const loading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref('添加分类')
const editingId = ref(null)

const columns = [
  {title: 'ID', dataIndex: 'id', key: 'id', width: 80},
  {title: '图标', key: 'icon', width: 100},
  {title: '分类名称', dataIndex: 'name', key: 'name'},
  {title: '描述', dataIndex: 'description', key: 'description', ellipsis: true},
  {title: '排序', dataIndex: 'sort', key: 'sort', width: 100},
  {title: '状态', key: 'status', width: 120},
  {title: '创建时间', dataIndex: 'createdAt', key: 'createdAt', width: 180},
  {title: '操作', key: 'action', width: 150, fixed: 'right'}
]

const dataSource = ref([])
const categoryTree = ref([])

// 生成父分类选择树数据（过滤掉正在编辑的分类）
const categoryTreeData = computed(() => {
  const filterNode = (nodes) => {
    return nodes
        .filter(node => node.id !== editingId.value)
        .map(node => ({
          ...node,
          children: node.children ? filterNode(node.children) : undefined
        }))
  }

  return [
    {id: 0, name: '顶级分类', children: filterNode(categoryTree.value)}
  ]
})

// 将树形数据扁平化为表格数据
const flattenTree = (tree, level = 0, result = []) => {
  tree.forEach(item => {
    result.push({
      ...item,
      level,
      isActive: item.status === 'ACTIVE'
    })
    if (item.children && item.children.length > 0) {
      flattenTree(item.children, level + 1, result)
    }
  })
  return result
}

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`
})

const formData = reactive({
  name: '',
  description: '',
  icon: '',
  parentId: 0,
  sort: 0
})

const showAddModal = () => {
  modalTitle.value = '添加分类'
  editingId.value = null
  Object.assign(formData, {
    name: '',
    description: '',
    icon: '',
    parentId: 0,
    sort: 0
  })
  modalVisible.value = true
}

const handleEdit = (record) => {
  modalTitle.value = '编辑分类'
  editingId.value = record.id
  Object.assign(formData, {
    name: record.name,
    description: record.description,
    icon: record.icon,
    parentId: record.parentId || 0,
    sort: record.sort || 0
  })
  modalVisible.value = true
}

const handleSubmit = async () => {
  if (!formData.name || formData.name.trim() === '') {
    message.warning('请输入分类名称')
    return
  }

  try {
    const submitData = {
      ...formData,
      parentId: formData.parentId || 0
    }

    if (editingId.value) {
      await updateCategory(editingId.value, submitData)
      message.success('更新成功')
    } else {
      await createCategory(submitData)
      message.success('添加成功')
    }
    modalVisible.value = false
    loadData()
  } catch (error) {
    console.error('操作失败:', error)
    message.error(error.response?.data?.message || error.message || '操作失败')
  }
}

const handleCancel = () => {
  modalVisible.value = false
}

const handleStatusChange = async (record) => {
  try {
    const newStatus = record.isActive ? 'ACTIVE' : 'INACTIVE'
    await updateCategoryStatus(record.id, newStatus)
    message.success('状态更新成功')
    loadData()
  } catch (error) {
    message.error('状态更新失败')
    record.isActive = !record.isActive
  }
}

const handleDelete = async (record) => {
  try {
    await deleteCategory(record.id)
    message.success('删除成功')
    loadData()
  } catch (error) {
    console.error('删除失败:', error)
    message.error(error.response?.data?.message || error.message || '删除失败')
  }
}

const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadData()
}

const loadData = async () => {
  loading.value = true
  try {
    const res = await getCategoryTree()
    if (res.code === 200) {
      categoryTree.value = res.data || []
      // 将树形数据扁平化用于表格展示
      const flatData = flattenTree(res.data || [])
      dataSource.value = flatData
      pagination.total = flatData.length
    } else {
      message.error(res.message || '加载数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.category-page {
  :deep(.ant-card) {
    margin-top: 16px;
  }

  :deep(.ant-table) {
    .ant-table-cell {
      vertical-align: middle;
    }
  }

  .card-shadow {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}
</style>

